package com.itheima.reggie.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;

import com.itheima.reggie.common.CustomException;
import com.itheima.reggie.entity.Dish;

import com.itheima.reggie.entity.DishFlavor;
import com.itheima.reggie.dto.Dishdto;
import com.itheima.reggie.mapper.DishMapper;

import com.itheima.reggie.service.DishFlavorService;
import com.itheima.reggie.service.DishService;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;

@Service
@Transactional
public class DishServiceImpl extends ServiceImpl<DishMapper, Dish> implements DishService {

    @Autowired
    public DishFlavorService dishFlavorService;


    @Override
    public void saveWithFlavor(Dishdto dishdto) {

        this.save(dishdto);

        Long id = dishdto.getId();

        List<DishFlavor> flavors = dishdto.getFlavors();

        for (DishFlavor flavor : flavors) {

            flavor.setDishId(id);
        }

        //批量保存菜品口味列表
        dishFlavorService.saveBatch(flavors);
    }

    @Override
    public Dishdto getByIdWithFlavor(Long id) {
        Dish dish = getById(id);
        Dishdto dishdto = new Dishdto();
        BeanUtils.copyProperties(dish,dishdto);

        LambdaQueryWrapper<DishFlavor> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(DishFlavor::getDishId,id);

        List<DishFlavor> list = dishFlavorService.list(wrapper);

        dishdto.setFlavors(list);

        return dishdto;


    }

    @Override
    public void updateWithFlavor(Dishdto dishdto) {

       updateById(dishdto);

        LambdaQueryWrapper<DishFlavor> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(DishFlavor::getDishId,dishdto.getId());
        dishFlavorService.remove(wrapper);

        List<DishFlavor> flavors = dishdto.getFlavors();
        for (DishFlavor flavor:flavors){

            flavor.setDishId(dishdto.getId());
        }

        dishFlavorService.saveBatch(flavors);

    }

    @Override
    public void removeWith(List<Long> ids) {
        LambdaQueryWrapper<Dish> wrapper = new LambdaQueryWrapper<>();
        wrapper.in(Dish::getId,ids).eq(Dish::getStatus,1);
        int count = this.count(wrapper);
        if (count>0){
            throw new CustomException("菜品正在售卖，不能删除");
        }
        this.removeByIds(ids);

        LambdaQueryWrapper<DishFlavor> wrapper1 = new LambdaQueryWrapper<>();
        wrapper1.in(DishFlavor::getDishId,ids);
        dishFlavorService.remove(wrapper1);

    }




}
